package com.hpe.aruba.CPPM.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.hpe.aruba.CPPM.R;
import com.hpe.aruba.CPPM.objects.Device;
import com.hpe.aruba.CPPM.utils.MacAdressUtils;

import java.util.ArrayList;
import java.util.List;

import static java.lang.String.join;

public class SwipeListAdapter extends RecyclerView.Adapter<SwipeListAdapter.MyViewHolder> implements Filterable {
    private List<Device> macList;
    private List<Device> filteredMacList;
    private static ArrayList<Device> staticMacList;
    private OnMacListener onMacListener;
    private boolean checkboxVisible;
    private Context context;


    public void showCheckboxes(boolean b) {
        checkboxVisible = b;
        notifyDataSetChanged();
    }

    public void getItemAt(int position) {
        //TODO update view toggle Item checkboxes
    }

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        CheckBox checkBox;
        public TextView name;
        public TextView listCol2;
        TextView vendor;
        RelativeLayout viewBackground;
        public RelativeLayout viewForeground;
        ImageView newDevice;

        MyViewHolder(View view) {
            super(view);
            checkBox = view.findViewById(R.id.checkBox);
            name = view.findViewById(R.id.name);
            vendor = view.findViewById(R.id.vendor);
            listCol2 = view.findViewById(R.id.status);
            viewBackground = view.findViewById(R.id.view_background);
            viewForeground = view.findViewById(R.id.view_foreground);
            newDevice = view.findViewById(R.id.newDevice);
            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (onMacListener != null) {
                onMacListener.onMacClicked(getAdapterPosition());
            }
        }
    }


    public SwipeListAdapter(Context context, List<Device> macList, OnMacListener onMacListener) {
        this.context = context;
        this.macList = macList;
        this.onMacListener = onMacListener;
        this.filteredMacList = macList;
        /*this.staticMacList = new ArrayList<>(macList);
        Doesn't work because it is called before macList is filled with information, therefore it stays empty*/
    }


    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.big_list_item, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {
        final Device item = macList.get(position);
        holder.name.setText(item.getMac());
        holder.vendor.setText( item.isEndpoint()?
                (item.getLast_known_location() == null || item.getLast_known_location().equals("")?
                        "unknown location" : item.getLast_known_location()):
                item.getVendor() == null || item.getVendor().equals("") ?
                        "unknown vendor" : item.getVendor()
        ); /*TODO BUG: Only performs categorization once, not for every single item in list*/
        holder.checkBox.setVisibility(checkboxVisible ? View.VISIBLE : View.GONE);
        holder.newDevice.setVisibility(item.isImported() ? View.INVISIBLE : View.VISIBLE);
        if (item.isEndpoint() == true){
            holder.listCol2.setText(item.getStatus());
        } else {
            holder.listCol2.setText(item.getRole_name());
        }
    }

    @Override
    public int getItemCount() {
        return macList.size();
    }

    public void removeItem(int position) {
        macList.remove(position);
        // notify the item removed by position
        // to perform recycler view delete animations
        // NOTE: don't call notifyDataSetChanged()
        notifyItemRemoved(position);
    }

    public void restoreItem(Device item, int position) {
        macList.add(position, item);
        // notify item added by position
        notifyItemInserted(position);
    }

    public interface OnMacListener {
        void onMacClicked(int position);
    }
    
    public void setOnMacListener(OnMacListener onMacListener) {
        this.onMacListener = onMacListener;
    }

    public void  setStaticMacs (ArrayList<Device> fullList){
        staticMacList = new ArrayList<>(fullList);
    }

    public ArrayList<Device> getStaticMacs (){
        return staticMacList;
    }
    
    
    
    public Filter getFilter() {
        return filter;
    }

    Filter filter = new Filter() {
        /**Filters for matching search results in mac-address list. charSequence is the users input in the searchbar.
         * If the charSequence is empty, then show all macs.
         * If there is a charSequence, then write all applicable macs to filteredMacList.
         */
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            if (charSequence.toString().isEmpty()) {
                filteredMacList = new ArrayList<>(staticMacList);
                Log.d("CLEARPASS", "All macs: " + macList);
            } else {
                filteredMacList = new ArrayList<>();
                String query = charSequence.toString().toLowerCase();
                for(Device mac: staticMacList) {
                    String baseMac = MacAdressUtils.baseMac(mac.getMac());
                    if (
                            mac.getMac().toLowerCase().contains(query) ||
                            baseMac.toLowerCase().contains(query) ||
                            mac.getLast_known_location().toLowerCase().contains(query) ||
                            mac.getVendor().toLowerCase().contains(query)
                    ) filteredMacList.add(mac);
                }
            }

            FilterResults filterResults = new FilterResults();
            filterResults.values = filteredMacList;
            filterResults.count = filteredMacList.size();
            Log.d("CLEARPASS", "Macs ready for publishing: " + filterResults.values);
            return filterResults;
        }


        /**
         *The applicable search results are now shown in the MacListview.
         * Changes should be undone, when back arrow in top left is pressed.
         */

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            macList.clear();
            macList.addAll((ArrayList<Device>) filterResults.values);
            notifyDataSetChanged();

            Log.d("CLEARPASS", "Update Macs was called with list:" + (ArrayList<Device>) filterResults.values);
            Log.d("CLEARPASS",  "Number of items in filtered list: " + filterResults.count);
            Log.d("CLEARPASS", "Number of items in macList" + getItemCount());
        }
    };
}